package com.example.ktdemo.span.view;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.ReplacementSpan;

/**
 * FileName: RoundBackgroundColorSpan
 * Author: lzt
 * Date: 2022/11/10 15:09
 * 居中--圆角round color span
 */
public class RoundBackgroundColorSpan extends ReplacementSpan {
    private int bgColor;
    private int textColor;
    private int radius;
    private int textSize;
    private int horizontalPadding;
    private boolean bold;

    public RoundBackgroundColorSpan(int bgColor, int textColor, int radius, int textSize) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
        this.radius = radius;
        this.textSize = textSize;
    }

    public RoundBackgroundColorSpan(int bgColor, int textColor, int radius, int textSize,
                                    int horizontalPadding, boolean bold) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
        this.radius = radius;
        this.textSize = textSize;
        this.horizontalPadding = horizontalPadding;
        this.bold = bold;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        paint.setTextSize(textSize);
        return ((int) paint.measureText(text, start, end) + horizontalPadding);
    }


    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {

        int color1 = paint.getColor();
        paint.setTextSize(textSize);

        paint.setColor(this.bgColor);
        RectF bgRectF = new RectF(x, top + 1, x + ((int) paint.measureText(text, start, end)) + horizontalPadding, bottom - 1);
        canvas.drawRoundRect(bgRectF, radius, radius, paint);

        paint.setColor(this.textColor);
        text = text.subSequence(start, end);
        Paint p = getCustomTextPaint(paint);
        Paint.FontMetricsInt fm = p.getFontMetricsInt();

        if (bold) {
            p.setTypeface(Typeface.DEFAULT_BOLD);
        } else {
            p.setTypeface(Typeface.DEFAULT);
        }

        canvas.drawText(text.toString(), x + horizontalPadding / 2, y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), p);


        paint.setColor(color1);
    }

    private TextPaint getCustomTextPaint(Paint srcPaint) {
        TextPaint paint = new TextPaint(srcPaint);
        paint.setTextSize(textSize);   //设定字体大小, sp转换为px
        return paint;
    }
}